package Sourcecode
import (
	_ "github.com/go-sql-driver/mysql"
	common "../Common"
	base "../dataBase"
	"fmt"
	"../model"
	_"reflect"
	"strconv"
	_"testing"
	dbc "../dataBase"
	"gopkg.in/mgo.v2/bson"
	"time"
)

func GetUserknowle() error{
	var db,err=base.GetMysqlDb()
	if(err!=nil){
		return common.New("链接Mysql数据库失败")
	}
	fmt.Println("创建连接")
	var t=time.Now().UnixNano()/1e6
	//查询数据库
	query, err := db.Query("SELECT t.TestpaperQuestionsID as 'UserknowledgepointID',t.CourseID,q.SyllabusKnowledgePointID,t.UserID,t.SubTime as 'AddTime',t.IsRight FROM testpaperquestions t LEFT JOIN questions q ON t.QuestionsID=q.Questionsid WHERE NOT(t.CourseID='' OR t.UserID='' OR t.IsRight=0) GROUP BY t.UserID,q.SyllabusKnowledgePointID,t.IsRight")
	if err != nil {
		fmt.Println("查询数据库失败", err.Error())
		return common.New("查询数据失败")
	}
	defer query.Close()
	fmt.Println("查询成功开始格式化数据")
	var t3=time.Now().UnixNano()/1e6
	//读出查询出的列字段名
	cols, _ := query.Columns()
	//values是每个列的值，这里获取到byte里
	values := make([][]byte, len(cols))
	//query.Scan的参数，因为每次查询出来的列是不定长的，用len(cols)定住当次查询的长度
	scans := make([]interface{}, len(cols))
	//让每一行数据都填充到[][]byte里面
	for i := range values {
		scans[i] = &values[i]
	}
	//最后得到的map
	results := make(map[int]Model.Userknowledgepoint)
	i := 0
	for query.Next() { //循环，让游标往下推
		if err := query.Scan(scans...); err != nil { //query.Scan查询出来的不定长值放到scans[i] = &values[i],也就是每行都放在values里
			fmt.Println(err)
			return err
		}

		row := make(map[string]interface{}) //每行数据

		for k, v := range values { //每行数据是放在values里面，现在把它挪到row里
			key := cols[k]
			row[key] = string(v)
		}
		addtime,_ :=strconv.ParseInt(row["AddTime"].(string),10,32)
		isright,_ :=strconv.ParseInt(row["IsRight"].(string),10,32)
		results[i] = Model.Userknowledgepoint{
			UserknowledgepointID :row["UserknowledgepointID"].(string),
			CourseID:row["CourseID"].(string),
			SyllabusKnowledgePointID:row["SyllabusKnowledgePointID"].(string),
			Userid:row["UserID"].(string),
			AddTime:int32(addtime),
			IsRight:int32(isright),
		}
		 //装入结果集中
		i++
	}

	//查询出来的数组
	fmt.Println("格式化完成开始导入数据")
	a,b:=0,0
	//for _, v := range results {
	//	var cha=make(chan int,100)
	//	go dbc.Insert("db","Userknowledgepoint",v,cha)
	//	if(<-cha==1){
	//		a++
	//	}else{
	//		b++
	//	}
	//	}
	for _, v := range results {
		selector := bson.M{"userknowledgepointID": v.UserknowledgepointID}
		data := bson.M{"$set": v}
		 dbc.Upsert("db","Userknowledgepoint",selector,data)
	}
	fmt.Printf("成功:%d,失败:%d\n",a,b)
	var t2=time.Now().UnixNano()/1e6
	fmt.Printf("共用时:%d,查询Mysql用时:%d\n",t2-t,t3-t)
	//fmt.Println("开始获取数据")
	//var arr []Model.Userknowledgepoint
	//dbc.FindAll("db","Userknowledgepoint",bson.M{},nil,&arr)
	////fmt.Print(arr)
	//fmt.Printf("共有数据%n",len(arr))
	db.Close() //用完关闭
	return nil

}

